import javax.xml.parsers.*;

import java.io.*;
import java.util.HashMap;

import org.w3c.dom.*;
import org.xml.sax.SAXException;

public class ParseManefistXML 
{
	//parse the xml file and get the proj2path map
	//write the map to a txt file
	private void getProj2PathMap(String srcXMLFile, String dstPath2NameMapFile) 
		throws SAXException, IOException
	{	
		//the proj-path map
		HashMap<String, String> proj2PathMap = new HashMap<String, String>();
		
		//for parsing xml file
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		Document xmlTree = null;
		
		try 
		{
			//Using factory get an instance of document builder
			DocumentBuilder db = dbf.newDocumentBuilder();

			//parse using builder to get DOM representation of the XML file
			xmlTree = db.parse(srcXMLFile);
			//yes
			//ss
		}
		catch(ParserConfigurationException pce) 
		{
			pce.printStackTrace();
		}
		catch(IOException ioe) 
		{
			ioe.printStackTrace();
		}
		
		//get and process the proj node list
		NodeList projList = xmlTree.getElementsByTagName("project");
		for (int i = 0; i < projList.getLength(); i++)
		{
			Node projNode = projList.item(i);
			projNode.normalize();
			
			NamedNodeMap projAttrList = projNode.getAttributes();
			
			//get attr name and path
			Node projNameNode = projAttrList.getNamedItem("name");
			Node projPathNode = projAttrList.getNamedItem("path");
			
			if (!(projNameNode == null && projPathNode == null))
			{
				projNameNode.normalize();
				projPathNode.normalize();
				
				String projName = projNameNode.getNodeValue();
				String projPath = projPathNode.getNodeValue();
				
				//System.out.println(projName + " : " + projPath);
				//dump it to the map
				proj2PathMap.put(projPath, projName);
			}
			
			Utilities.writeMapToFile(proj2PathMap, dstPath2NameMapFile);
		}	
	}
	
	public static void main(String args[]) throws SAXException, IOException
	{
		ParseManefistXML fuyun = new ParseManefistXML();
		
		fuyun.getProj2PathMap("data/android-4.0.1/tmp.xml",
				"data/android-4.0.1/projPath2NameMap.csv");
	}
}
